const mongoose = require('mongoose');
const User = require('../models/user.model');
var multer = require('multer');
var path = require('path');

var storage = multer.diskStorage({
	destination:function(req,file,cb){
		cb(null,'./uploads')
	},
	filename:function(req,file,cb){
		cb(null,file.filename + '-' + Date.now() + path.extname(file.originalname))
	}
})

var upload = multer({storage:storage})

exports.upload = function(req,res,next){
	var upload = multer({
		storage:storage,
		fileFilter:function(req,file,cb){
			var ext = path.extname(file.originalname)
			if(ext !== '.png' && ext!== '.jpg' && ext !== '.gif' && ext!=='.jpeg'){
				return cb(res.end('Only images are allowed'),null)
			}
			cb(null,true)
		}
	})
	.single('avatar');
	upload(req,res,function(err){
		res.end('File is uploaded')
	})
}

//新建用户

exports.create = function(req,res,next){
	var name = req.body.name;
	User.findOne({'name':name},function(err,results){
		if(results){
			res.json({msg:true})
		}else{
			const user = new User(req.body);
			user.save().then((data)=>{
				res.json(data)
			})
		}
	})
	
};

//登录

exports.login = function(req,res,next){
	User.findOne({'name':req.body.name,'password':req.body.password},function(err,data){
		res.json(data);
	})
}

exports.update = function(req,res,next){
	const user = new User(req.body);
	const name = req.params.name;


	User.findOneAndUpdate(name,{$set:req.body},{new:false})
		.then((user)=>{
			res.send({user});
		})
}

exports.isSet = function(req,res,next){
	var name = req.body.name;
	User.findOne({'name':name},function(err,results){
		if(results){
			res.json({msg:true})
		}else{
			res.json({msg:false})
		}
	})
	
};

exports.getall = function(req,res,next){
	User.find().then(data=>{
		res.json(data);
	})
}

exports.list = function(req,res,next){
	var page = (req.body.page) ? req.body.page:1;
	var limit = (req.body.limit)?req.body.limit:8;
	var queryCondition = {};
	if(req.body.name && req.body.name.trim().length>0){
		name = req.body.name;
		queryCondition={
			"name":new RegExp(name,"i")
		}
	}

	User.paginate(queryCondition,{page:page,limit:limit},function(err,results){
		res.json(results);
	});
}

exports.removes = function(req,res,next){
	var name = req.body.name;
	var data={name:name};
	User.remove(data,function(err,doc){
		res.json({"msg":"delete ok"});
	})
}

exports.removeusers = function(req,res,next){
	var users = req.body.users;
	if(users.length>0){
		User.remove({name:{$in:users}})
		.then(deleted=>{
			res.json({"msg":"delete ok"});
		})
	}
}